import React, { useState } from 'react';
import { Dialog, Input, Message } from '@alifd/next';
import { IPublicModelPluginContext, IPublicEnumTransformStage } from '@alilc/lowcode-types';
import { addCustomComponent, generateComponentId } from '../utils/storage';

interface WrapperDialogProps {
  ctx: IPublicModelPluginContext;
  visible: boolean;
  onClose: () => void;
}

const WrapperDialog: React.FC<WrapperDialogProps> = ({ ctx, visible, onClose }) => {
  const [title, setTitle] = useState('');
  const [componentName, setComponentName] = useState('');
  const [description, setDescription] = useState('');

  const handleOk = () => {
    if (!title.trim() || !componentName.trim()) {
      Message.error('请填写组件标题和组件名称');
      return;
    }

    try {
      const { project } = ctx;
      const currentDocument = project.currentDocument;

      if (!currentDocument) {
        Message.error('没有找到当前文档');
        return;
      }

      const selection = currentDocument.selection;
      const selectedNodes = selection.getTopNodes();

      if (!selectedNodes || selectedNodes.length === 0) {
        Message.error('请先选择要封装的组件');
        return;
      }

      // 获取第一个选中节点的 schema
      const selectedNode = selectedNodes[0];
      const schema = selectedNode.exportSchema(IPublicEnumTransformStage.Save);

      // 创建自定义组件
      const customComponent = {
        id: generateComponentId(),
        componentName: componentName.trim(),
        title: title.trim(),
        description: description.trim(),
        schema,
        createTime: Date.now(),
      };

      // 保存到 localStorage
      addCustomComponent(customComponent);

      // 发送事件通知组件列表刷新
      const { event } = ctx;
      event.emit('customComponent:refresh');

      Message.success(`组件 "${title}" 封装成功！`);

      // 重置表单并关闭对话框
      setTitle('');
      setComponentName('');
      setDescription('');
      onClose();
    } catch (error) {
      console.error('封装组件失败:', error);
      Message.error('封装组件失败，请查看控制台');
    }
  };

  const handleCancel = () => {
    setTitle('');
    setComponentName('');
    setDescription('');
    onClose();
  };

  return (
    <Dialog
      title="封装自定义组件"
      visible={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      onClose={handleCancel}
    >
      <div style={{ padding: '20px 0' }}>
        <div style={{ marginBottom: '16px' }}>
          <div style={{ marginBottom: '8px' }}>
            组件标题 <span style={{ color: 'red' }}>*</span>
          </div>
          <Input
            placeholder="请输入组件标题"
            value={title}
            onChange={(value) => setTitle(String(value))}
          />
        </div>

        <div style={{ marginBottom: '16px' }}>
          <div style={{ marginBottom: '8px' }}>
            组件名称 <span style={{ color: 'red' }}>*</span>
          </div>
          <Input
            placeholder="请输入组件名称（英文，如 MyButton）"
            value={componentName}
            onChange={(value) => setComponentName(String(value))}
          />
        </div>

        <div style={{ marginBottom: '16px' }}>
          <div style={{ marginBottom: '8px' }}>组件描述</div>
          <Input.TextArea
            placeholder="请输入组件描述（选填）"
            value={description}
            onChange={(value) => setDescription(String(value))}
            rows={3}
          />
        </div>

        <div style={{ padding: '12px', background: '#f5f5f5', borderRadius: '4px', fontSize: '12px', color: '#666' }}>
          <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>说明：</div>
          <div>1. 请先在画布中选择要封装的组件</div>
          <div>2. 组件会保存当前的结构和属性配置</div>
          <div>3. 封装后可在"查看组件"中管理</div>
        </div>
      </div>
    </Dialog>
  );
};

export default WrapperDialog;
